package com.whmnx.login.ui.model;

import android.app.Application;
import android.text.TextUtils;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.databinding.ObservableField;
import androidx.databinding.ObservableInt;

import com.alibaba.android.arouter.launcher.ARouter;
import com.mob.MobSDK;
import com.mob.OperationCallback;
import com.whmnx.base.bean.LoginBean;
import com.whmnx.base.bean.UserBean;
import com.whmnx.base.constants.Constants;
import com.whmnx.base.http.CallBack;
import com.whmnx.base.http.HttpClient;
import com.whmnx.base.router.RouterActivityPath;
import com.whmnx.base.router.RouterFragmentPath;
import com.whmnx.base.utils.CodeTimeUtils;
import com.whmnx.base.utils.UItils;
import com.whmnx.login.databinding.ActivityLoginBinding;
import com.whmnx.login.ui.ForgetPassWordFragment;
import com.whmnx.login.ui.LoginActivity;

import java.util.HashMap;
import java.util.Map;

import me.goldze.mvvmhabit.base.BaseViewModel;
import me.goldze.mvvmhabit.binding.command.BindingAction;
import me.goldze.mvvmhabit.binding.command.BindingCommand;
import me.goldze.mvvmhabit.bus.event.SingleLiveEvent;
import me.goldze.mvvmhabit.utils.SPUtils;
import me.goldze.mvvmhabit.utils.ToastUtils;

/**
 * author : huang
 * date   : 2020/9/16 0016 17:29
 * version: 1.0
 * @author Administrator
 */
public class LoginViewModel extends BaseViewModel {

    private boolean flag = false;
    private LoginActivity mContext;
    //用户名的绑定
    public ObservableField<String> userName = new ObservableField<>("");
    //密码的绑定
    public ObservableField<String> password = new ObservableField<>("");

    public ObservableField<String> code = new ObservableField<>("");
    public ObservableField<String> loginPas = new ObservableField<>("");
    public ObservableField<String> renPas = new ObservableField<>("");
    public ObservableField<String> payPas = new ObservableField<>("");
    public ObservableField<String> renPayPas = new ObservableField<>("");
    public ObservableField<String> yaoPas = new ObservableField<>("");
    public ObservableField<String> login = new ObservableField<>("登录");
    //用户名清除按钮的显示隐藏绑定
    public ObservableInt viewVisibility = new ObservableInt(View.VISIBLE);

    public ObservableInt view2Visibility = new ObservableInt(View.GONE);
    public ObservableInt codeVisibility = new ObservableInt(View.GONE);
    public ObservableInt loginPasVisibility = new ObservableInt(View.VISIBLE);
    public ObservableInt renloginPasVisibility = new ObservableInt(View.VISIBLE);
    public ObservableInt payPasVisibility = new ObservableInt(View.VISIBLE);
    public ObservableInt renpayPasVisibility = new ObservableInt(View.VISIBLE);
    public ObservableInt yaoPasVisibility = new ObservableInt(View.VISIBLE);
    public ObservableInt pasVisibility = new ObservableInt(View.VISIBLE);
    public ObservableInt llVisibility = new ObservableInt(View.GONE);

    //封装一个界面发生改变的观察者
    public UIChangeObservable uc = new UIChangeObservable();

    ActivityLoginBinding mBinding;
    private String code2;

    public void initData(LoginActivity loginActivity, ActivityLoginBinding binding) {
        this.mContext = loginActivity;
        this.mBinding = binding;
    }


    public class UIChangeObservable {
        //密码开关观察者
        public SingleLiveEvent<Boolean> pSwitchEvent = new SingleLiveEvent<>();
    }


    public LoginViewModel(@NonNull Application application) {
        super(application);
    }



    //登录按钮的点击事件
    public BindingCommand loginOnClickCommand = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            login();
        }
    });

    //
    public BindingCommand yingOnClickCommand = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            SPUtils.getInstance().put("code", 5);
            ARouter.getInstance().build(RouterFragmentPath.User.MY_GUANLI).navigation();
        }
    });

    public BindingCommand youOnClickCommand = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            SPUtils.getInstance().put("code", 4);
            ARouter.getInstance().build(RouterFragmentPath.User.MY_GUANLI).navigation();
        }
    });

    //上方 登录按钮的点击事件
    public BindingCommand llLoginOnClickCommand = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            flag = false;
            viewVisibility.set(View.VISIBLE);
            view2Visibility.set(View.INVISIBLE);
            pasVisibility.set(View.VISIBLE);
            llVisibility.set(View.GONE);
            codeVisibility.set(View.GONE);
            login.set("登录");
            mBinding.ll2.setVisibility(View.INVISIBLE);
            //让观察者的数据改变,逻辑从ViewModel层转到View层，在View层的监听则会被调用
            uc.pSwitchEvent.setValue(true);
        }
    });
    //上方 注册按钮的点击事件
    public BindingCommand llRegistOnClickCommand = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            flag = true;
            view2Visibility.set(View.VISIBLE);
            viewVisibility.set(View.INVISIBLE);
            pasVisibility.set(View.GONE);
            llVisibility.set(View.VISIBLE);
            codeVisibility.set(View.VISIBLE);
            login.set("注册");
            //让观察者的数据改变,逻辑从ViewModel层转到View层，在View层的监听则会被调用
            uc.pSwitchEvent.setValue(false);
            mBinding.ll2.setVisibility(View.VISIBLE);
        }
    });

    //忘记密码按钮的点击事件
    public BindingCommand wangJiPasOnClickCommand = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            startContainerActivity(ForgetPassWordFragment.class.getCanonicalName());
        }
    });
    //验证码的点击事件
    public BindingCommand codeOnClickCommand = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
             getCode();
        }
    });

    private void getCode() {
        if (!UItils.isPhoneNumber(userName.get())){
            ToastUtils.showShort("请输入手机号！");
            return;
        }

        Map<String, Object> params = new HashMap<>();
        params.put("Mobile",userName.get());
        HttpClient.get(mContext,Constants.GETCODE, params,new CallBack<String>() {
            @Override
            public void onSuccess(String result) {
                code2 = result;
                CodeTimeUtils.countDowns(mBinding.tvCode);

            }
        });
    }


    /**
     * 网络模拟一个登陆操作
     **/
    private void login() {
        if (!UItils.isPhoneNumber(userName.get())) {
            ToastUtils.showShort("请输入手机号！");
            return;
        }
        if (!flag) {
            if (TextUtils.isEmpty(password.get())) {
                ToastUtils.showShort("请输入密码！");
                return;
            }
        }
        if (flag) {
            if (TextUtils.isEmpty(code.get())) {
                ToastUtils.showShort("请输入验证码！");
                return;
            }
            if (TextUtils.isEmpty(loginPas.get())) {
                ToastUtils.showShort("请输入登录密码！");
                return;
            }

            if (TextUtils.isEmpty(renPas.get())) {
                ToastUtils.showShort("请输入确认登录密码！");
                return;
            }
            if (TextUtils.isEmpty(payPas.get())) {
               ToastUtils.showShort("请输入交易密码！");
                return;
            }
            if (TextUtils.isEmpty(renPayPas.get())) {
                ToastUtils.showShort("请输入确认交易密码！");
                return;
            }
            if (!loginPas.get().equals(renPas.get())){
                ToastUtils.showShort("2次输入密码不一致！");
                return;
            }
            if (!payPas.get().equals(renPayPas.get())){
                ToastUtils.showShort("2次输入交易密码不一致！");
                return;
            }
            if (mBinding.cb.isChecked()){
                MobSDK.submitPolicyGrantResult(true, new OperationCallback<Void>() {
                    @Override
                    public void onComplete(Void data) {
                        // Log.d(TAG, "隐私协议授权结果提交：成功");
                    }

                    @Override
                    public void onFailure(Throwable t) {
                        // Log.d(TAG, "隐私协议授权结果提交：失败");
                    }
                });
            }else {
                ToastUtils.showShort("请阅读并同意");
                return;
            }
        }
        //注册
        if (flag){
            //可以调用addSubscribe()添加Disposable，请求与View周期同步
            Map<String, Object> params = new HashMap<>();
            params.put("userInfo_Mobile",userName.get());
            params.put("userInfo_Mobile",userName.get());
            params.put("code",code.get());
            params.put("parentID",yaoPas.get());
            params.put("userInfo_Pwd",UItils.md5Digest(loginPas.get()));
            params.put("userInfo_SafePwd",UItils.md5Digest(renPas.get()));
            HttpClient.post(mContext,Constants.REGISTER, params,new CallBack<UserBean>() {
                @Override
                public void onSuccess(UserBean result) {

                }
            });
        }else {
            //登录
            Map<String, Object> params = new HashMap<>();
            params.put("phone",userName.get());
            params.put("pwd",UItils.md5Digest(password.get()));
           // ARouter.getInstance().build(RouterActivityPath.Main.PAGER_MAIN).navigation();
         //   finish();
            HttpClient.post(mContext,Constants.LOGIN, params,new CallBack<LoginBean>() {
                @Override
                public void onSuccess(LoginBean result) {
                    SPUtils.getInstance().put(Constants.LOGIN2, true);
                    SPUtils.getInstance().put(Constants.TOKEN, result.getToken());
                    SPUtils.getInstance().put(Constants.USERID, result.getAppuser().getUserId());
                    SPUtils.getInstance().put(Constants.PHONE, result.getAppuser().getPhone());
                    SPUtils.getInstance().put(Constants.HEAD_IMG, result.getAppuser().getAvatar());
                    SPUtils.getInstance().put(Constants.NICKNAME, result.getAppuser().getName());
                    ARouter.getInstance().build(RouterActivityPath.Main.PAGER_MAIN).navigation();
                    finish();
                }
            });
        }
    }
}
